package sk.naive.talker.command;

import sk.naive.talker.*;
import sk.naive.talker.adapter.TagConsts;
import sk.naive.talker.props.PropertyStoreException;
import sk.naive.talker.util.*;
import sk.naive.talker.message.DefaultMessageFactory;

import java.rmi.RemoteException;
import java.util.*;

/**
 * @author <a href="mailto:rytier@naive.deepblue.sk">Martin "Rytier" Kerni</a>
 * @version $Revision: 1.7 $ $Date: 2005/01/18 20:51:30 $
 */
public class UserAdmin extends AbstractCommand {
	public void exec() throws RemoteException, CommandException, PropertyStoreException {
		Utils.checkPermission(user, Consts.PERM_SUPERUSER);
		UserFinder uf = commandDispatcher.getUserFinder();
		Set<String> sortedLogins = new TreeSet<String>();
		sortedLogins.addAll(uf.getUserLogins());
		StringBuilder sb = new StringBuilder();
		long current = System.currentTimeMillis();
		ctxSet(DefaultMessageFactory.CTXKEY_VAL + "currentDate", Utils.createDate(current));
		sb.append(getString("userAdmin.head", user.getProperties()));
		int count = 0;
		for (String login : sortedLogins) {
			User u2 = (User) uf.findUserByLogin(login);
			UserContextHelper u2ContextHelper = new UserContextHelper(u2);
			String afkTime = getString("userAdmin.off", u2.getProperties());
			if (uf.findLoggedUser(login) != null) {
				StringBuilder timeSb = new StringBuilder();
				long loginTime = (Long) u2.get(User.UPROP_LOGIN_TIME);
				long lastAction = (Long) u2.get(User.UPROP_LAST_ACTION_TIME);
				timeSb.append(Utils.createLong(current - loginTime, Consts.MINUTE_MILLIS));
				timeSb.append("/");
				timeSb.append(Utils.createLong(current - lastAction, Consts.MINUTE_MILLIS));
				afkTime = timeSb.toString();
			}
			u2ContextHelper.set(DefaultMessageFactory.CTXKEY_VAL + "AfkTime", afkTime);
			u2ContextHelper.set(DefaultMessageFactory.CTXKEY_VAL + "TLTime", Utils.createLong(u2.get(User.UPROP_TOTAL_LOGIN_TIME), Consts.MINUTE_MILLIS));

			if (u2 == user) {
				sb.append(getString("userAdmin.selfline", u2.getProperties()));
			} else {
				sb.append(getString("userAdmin.line", u2.getProperties(), user.getLang()));
			}
			u2ContextHelper.cleanup();
			count++;
		}
		ctxSet(DefaultMessageFactory.CTXKEY_VAL, String.valueOf(count));
		sb.append(getString("userAdmin.tail", user.getProperties()));
		sb.append(Utils.tag(TagConsts.PAGING));
		user.send(sb.toString());
	}
}
